import sys
import socket
import shlex, subprocess

if len(sys.argv) != 3:
	print 'usage: python udpJoystick.py <receiver-IP> <receiver-Port>'
	exit(-1)

UDP_IP=sys.argv[1]
UDP_PORT=int(sys.argv[2])


#create and launch ping-subprocess
pingArgs = shlex.split("ping " + sys.argv[1]);
p = subprocess.Popen(pingArgs);

print 'Starting udpJoystick with target IP ' + sys.argv[1] + ' and port ' + sys.argv[2]

sock = socket.socket( socket.AF_INET, # Internet
                       socket.SOCK_DGRAM ) # UDP

pipe = open('/dev/input/js0','r')
action = []
spacing = 0
while 1:
	for character in pipe.read(1):
		action += ['%02X' % ord(character)]
		if len(action) == 8:

			num = int(action[5], 16) # Translate back to integer form
			# calculate values between 0 and 25
			signal2 = (256+127-num)/10
			signal = (127-num)/10

			if action[6] == '01': # Button
				if action[4] == '01':
					print 'You pressed button: ' + action[7]
					sock.sendto( action[7], (UDP_IP, UDP_PORT) )
				else:
					print 'You released button: ' + action[7]
					sock.sendto( action[7] + ' released', (UDP_IP, UDP_PORT) )

			elif action[7] == '00': # D-pad left/right
				num = int(action[5], 16) # Translate back into integer form
				if num >= 128:
					signal2 = signal2 + 60
					print 'You steer to ' + str(signal2)
					sock.sendto( str(signal2), (UDP_IP, UDP_PORT) )
				elif num <= 127 :
					signal = signal + 60
					print 'You steer to ' + str(signal)
					sock.sendto( str(signal), (UDP_IP, UDP_PORT) )
				else:
					print 'Error moving the joystick'


			elif action[7] == '01': # accelerator
				num = int(action[5], 16) # Translate back into integer form
				if num >= 128:
					signal2 = 32 -signal2/2
					# signal2 = 45-signal2
					print 'You moved the accelerator to ' + str(signal2)
					sock.sendto( str(signal2), (UDP_IP, UDP_PORT) )
				elif num <= 127 :
					signal = 32 - signal/2
					# signal = 45-signal
					print 'You moved the accelerator to ' + str(signal)
					sock.sendto( str(signal), (UDP_IP, UDP_PORT) )
				else:
					print 'Error moving the joystick'



			elif action[7] == '02': # Left pedal (break)
				num = int(action[5], 16) # Translate back into integer form
				if num >= 128:
					signal2 = 32 + signal2/2
					# signal2 = 32-signal2
					print 'You moved the break to ' + str(signal2)
					sock.sendto( str(signal2), (UDP_IP, UDP_PORT) )
				elif num <= 127 :
					signal = 32 + signal/2
					# signal = 32-signal
					print 'You moved the break to ' + str(signal)
					sock.sendto( str(signal), (UDP_IP, UDP_PORT) )
				else:
					print 'Error moving the joystick'
			action = []

